from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.models import User
from django.db.models import Q
from .models import Profile as UserProfile

@login_required
def user_list(request):
    """用户列表 - 管理员功能"""
    if not request.user.is_staff:
        messages.error(request, '您没有权限访问用户管理')
        return redirect('dashboard')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        users = User.objects.filter(
            Q(username__icontains=search_query) |
            Q(first_name__icontains=search_query) |
            Q(last_name__icontains=search_query) |
            Q(email__icontains=search_query)
        ).select_related('profile')
    else:
        users = User.objects.all().select_related('profile')
    
    # 角色筛选
    role_filter = request.GET.get('role', '')
    if role_filter:
        users = users.filter(profile__role=role_filter)
    
    context = {
        'users': users.order_by('-date_joined'),
        'search_query': search_query,
        'role_filter': role_filter,
        'role_choices': UserProfile.ROLE_CHOICES,
    }
    return render(request, 'users/list.html', context)

@login_required
def user_detail(request, pk):
    """用户详情 - 管理员功能"""
    if not request.user.is_staff:
        messages.error(request, '您没有权限查看用户详情')
        return redirect('dashboard')
    
    user = get_object_or_404(User.objects.select_related('profile'), pk=pk)
    
    # 获取用户活动统计数据
    from tickets.models import Ticket, MaintenanceRecord
    from assets.models import Asset
    
    created_tickets = Ticket.objects.filter(created_by=user).count()
    assigned_tickets = Ticket.objects.filter(assigned_to=user).count()
    owned_assets = Asset.objects.filter(assigned_to=user).count()
    maintenance_records = MaintenanceRecord.objects.filter(technician=user).count()
    
    context = {
        'target_user': user,
        'role_choices': UserProfile.ROLE_CHOICES,
        'created_tickets': created_tickets,
        'assigned_tickets': assigned_tickets,
        'owned_assets': owned_assets,
        'maintenance_records': maintenance_records,
    }
    return render(request, 'users/detail.html', context)

@login_required
def user_edit(request, pk):
    """编辑用户信息 - 管理员功能"""
    if not request.user.is_staff:
        messages.error(request, '您没有权限编辑用户信息')
        return redirect('dashboard')
    
    user = get_object_or_404(User.objects.select_related('profile'), pk=pk)
    
    if request.method == 'POST':
        # 更新用户基本信息
        user.first_name = request.POST.get('first_name', user.first_name)
        user.last_name = request.POST.get('last_name', user.last_name)
        user.email = request.POST.get('email', user.email)
        user.is_active = request.POST.get('is_active') == 'true'
        
        # 更新用户密码（如果提供了新密码）
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        
        if new_password:
            if new_password != confirm_password:
                messages.error(request, '密码确认不匹配')
                return render(request, 'users/edit.html', {
                    'target_user': user,
                    'role_choices': UserProfile.ROLE_CHOICES,
                })
            
            if len(new_password) < 6:
                messages.error(request, '密码长度至少需要6个字符')
                return render(request, 'users/edit.html', {
                    'target_user': user,
                    'role_choices': UserProfile.ROLE_CHOICES,
                })
            
            user.set_password(new_password)
            messages.success(request, '用户密码已更新')
        
        # 更新用户角色
        if hasattr(user, 'profile'):
            user.profile.role = request.POST.get('role', user.profile.role)
            user.profile.phone = request.POST.get('phone', user.profile.phone)
            user.profile.save()
        
        user.save()
        messages.success(request, f'用户 {user.username} 信息更新成功')
        return redirect('users:user_detail', pk=user.pk)
    
    context = {
        'target_user': user,
        'role_choices': UserProfile.ROLE_CHOICES,
    }
    return render(request, 'users/edit.html', context)

@login_required
def user_create(request):
    """创建新用户 - 管理员功能"""
    if not request.user.is_staff:
        messages.error(request, '您没有权限创建用户')
        return redirect('dashboard')
    
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        role = request.POST.get('role', 'customer')
        
        if User.objects.filter(username=username).exists():
            messages.error(request, '用户名已存在')
            return render(request, 'users/create.html', {
                'role_choices': UserProfile.ROLE_CHOICES,
                'form_data': request.POST
            })
        
        if User.objects.filter(email=email).exists():
            messages.error(request, '邮箱已存在')
            return render(request, 'users/create.html', {
                'role_choices': UserProfile.ROLE_CHOICES,
                'form_data': request.POST
            })
        
        try:
            user = User.objects.create_user(
                username=username,
                email=email,
                password=password,
                first_name=first_name,
                last_name=last_name
            )
            
            # 检查是否已经存在Profile（由于信号可能已经创建）
            if not hasattr(user, 'profile'):
                # 创建用户配置文件
                UserProfile.objects.create(
                    user=user,
                    role=role,
                    phone=request.POST.get('phone', '')
                )
            else:
                # 更新现有的Profile
                user.profile.role = role
                user.profile.phone = request.POST.get('phone', '')
                user.profile.save()
            
            messages.success(request, f'用户 {username} 创建成功')
            return redirect('users:user_list')
            
        except Exception as e:
            messages.error(request, f'创建用户失败: {str(e)}')
            return render(request, 'users/create.html', {
                'role_choices': UserProfile.ROLE_CHOICES,
                'form_data': request.POST
            })
    
    context = {
        'role_choices': UserProfile.ROLE_CHOICES,
    }
    return render(request, 'users/create.html', context)

@login_required
def user_toggle_active(request, pk):
    """启用/禁用用户 - 管理员功能"""
    if not request.user.is_staff:
        messages.error(request, '您没有权限执行此操作')
        return redirect('dashboard')
    
    user = get_object_or_404(User, pk=pk)
    
    if user == request.user:
        messages.error(request, '不能禁用当前登录的用户')
        return redirect('users:user_detail', pk=user.pk)
    
    user.is_active = not user.is_active
    user.save()
    
    status = "启用" if user.is_active else "禁用"
    messages.success(request, f'用户 {user.username} 已{status}')
    return redirect('users:user_detail', pk=user.pk)
